import fw from '../framework.js'
import program from './program.js'
import channel from './channel.js'
import publish from './publish.js'

function publishByProgramData(opts){
    if(opts.type == 'create'){
        program.create(opts.data,function(res){
            publishByProgramId({
                terminalIds:opts.terminalIds,
                programId:res.id,
                success:opts.success,
                error:opts.error
            });
        },function(res){
            if(opts.error)opts.error(res,'createProgram');
        })
    }else{
        program.update(opts.data,function(res){
            publishByProgramId({
                terminalIds:opts.terminalIds,
                programId:res.id,
                success:opts.success,
                error:opts.error
            });
        },function(res){
            if(opts.error)opts.error(res,'updateProgram');
        })
    }
}
function publishByProgramId(opts){
    channel.create(opts.programId,function(channelData){
        publish.publishTerminal(opts.terminalIds,channelData.id,function(res){
            if(opts.success)opts.success(res,'publish')
        },function(res){
            if(opts.error)opts.error(res,'publish')
        })
    },function(res){
        if(opts.error)opts.error(res,'createChannel');
    })
}

function publishByChannelId(opts){
    if(opts.type == 'tag'){
        publish.publishTag(opts.tags,opts.channelId,function(res){
            if(opts.success)opts.success(res,'publish')
        },function(res){
            if(opts.error)opts.error(res,'publish')
        })
    }else{
        publish.publishTerminal(opts.terminalIds,opts.channelId,function(res){
            if(opts.success)opts.success(res,'publish')
        },function(res){
            if(opts.error)opts.error(res,'publish')
        })
    }  
}

module.exports = {
    publishByProgramData:publishByProgramData,
    publishByProgramId:publishByProgramId,
    publishByChannelId:publishByChannelId,
    program:program,
    channel:channel,
    publish:publish
}
